package database

import (
	"context"
	"log"
	"time"

	"github.com/AiGenApps/goout-server/config"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var (
	Client *mongo.Client
)

// InitMongoDB 初始化MongoDB连接
func InitMongoDB() error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// 创建MongoDB客户端
	clientOptions := options.Client().ApplyURI(config.MongoURI)
	client, err := mongo.Connect(ctx, clientOptions)
	if err != nil {
		log.Printf("MongoDB连接失败: %v", err)
		return err
	}

	// 测试连接
	err = client.Ping(ctx, nil)
	if err != nil {
		log.Printf("MongoDB Ping失败: %v", err)
		return err
	}

	Client = client
	log.Println("MongoDB连接成功")
	return nil
}

// CloseMongoDB 关闭MongoDB连接
func CloseMongoDB() {
	if Client != nil {
		if err := Client.Disconnect(context.Background()); err != nil {
			log.Printf("MongoDB断开连接失败: %v", err)
		}
	}
}

// GetCollection 获取指定集合
func GetCollection(database, collection string) *mongo.Collection {
	return Client.Database(database).Collection(collection)
}
